﻿using System;
using System.Collections;
using UnityEngine;

/// <summary>
/// 资源管理器
/// </summary>
public class ResMgr : Singleton<ResMgr>
{
    /// <summary>
    /// 实例化一个GameObject
    /// </summary>
    public GameObject InstanceGameObject(string path, Vector3? pos = null)
    {
        if (!pos.HasValue)
        {
            return GameObject.Instantiate(Resources.Load(path)) as GameObject;
        }
        return GameObject.Instantiate(Resources.Load(path), pos.Value, Quaternion.Euler(Vector3.zero)) as GameObject;
    }

    /// <summary>
    /// 加载模板(简单封装)
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    public UnityEngine.Object LoadTemplate(string path)
    {
        return Resources.Load(path);
    }

    internal byte[] LoadConfig(string path)
    {
        return Resources.Load<TextAsset>(path).bytes;
    }

    public void ReleaseObject(UnityEngine.Object obj)
    {
        GameObject.Destroy(obj);
    }

    /// <summary>
    /// 延迟回收
    /// </summary>
    public void AutoRecycleWithSecond(GameObject obj, float time)
    {
        QuickCoroutine.instance.Go.StartCoroutine(
            Utils.CallbackWithSecond(time, () => ResMgr.instance.ReleaseObject(obj)));
    }

    /// <summary>
    /// 帧结束回收
    /// </summary>
    public void AutoRecycleWithEndOfFrame(GameObject obj)
    {
        QuickCoroutine.instance.Go.StartCoroutine(
            Utils.CallbackWithFixedUpdate(() => ResMgr.instance.ReleaseObject(obj)));
    }
}
